package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.PriceBean;
import com.gongpingjialoan.bean.SellRecordBean;
import com.gongpingjialoan.bean.VipBuycarBean;
import com.gongpingjialoan.data.CarListFilterData;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.TimeUtils;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.CircleView;
import com.gongpingjialoan.view.GetPhoneDialog;
import com.gongpingjialoan.view.PriceChangeView;
import com.gongpingjialoan.view.PriceRegionView;
import com.gongpingjialoan.view.VipBuyCarDialog;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.gongpingjialoan.R.id.circleView;

/**
 * Created by Administrator on 2016/1/27.
 */
public class NewUseCarAssResultActivity extends BaseActivity implements PopupWindow.OnDismissListener, View.OnClickListener, AdapterView.OnItemClickListener,
        NetDataJson.OnNetDataJsonListener {

    private ListView mListView;

    private View headV, priceChangeMain, nocar_headView;

    private ImageView mImageView;

    private List<CarSource> mCarSourceList;

    private NetDataJson mNetCarSource;

    private NetDataJson carListnetWork;

    private CarSourceListAdapter mAdapter;
    // 个人二手车的价格
    private TextView private_party_priceT;
    // 认证二手车价格
    private TextView cpo_priceT;
    // 商家二手车价
    private TextView dealer_priceT;

    private TextView popupTextView;

    private TextView carNameTextView, carTimeTextView, carPriceTextView, gbTextView, price_rangeTextView;

    private static final int LOGINING_FORSEECAR = 4;
    // 估值时保存的数据
    private AssessmentData assessmentData;

    private PopupWindow mPopupWindow, vipPopupWindow;

    private View popupView, vip_popupView;

    private PriceChangeView mPriceChangeView;

    private View circleMain;

    private CircleView mCircleView;

    private Button vipButton;

    private TextView vipTextView;

    private VipBuyCarDialog vipBuyCarDialog;

    private String tilte, price, imageUrl;

    private NetDataJson mSellRecordNetDataJson;

    private SellRecordBean mSellRecordBean = new SellRecordBean();

    private boolean isLoadState = true;
    private LinearLayout more_ll;
    private LinearLayout sell_record_ll;
    private TextView load_state_tv;
    private ImageView load_state_img;
    private LinearLayout include_sell_record_ll;
    private TextView recommed_tv;
    private TextView num_tv;
    private GetPhoneDialog getPhoneDialog;

    private PriceRegionView lineView;

    private String avg_buy;

    TextView recommed_moreT;
    private LinearLayout recommed_ll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "eval_buy";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.used_car_ass_layout);
        setTitle("买车查价详情");
        initView();

        initData();
        initSellRecord();

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                mPopupWindow.dismiss();
            } else if (msg.what == 2) {
                vipPopupWindow.dismiss();
            }
        }
    };

    @Override
    protected void onDestroy() {
        action = "eval_buy";
        super.onDestroy();
        if (mNetCarSource != null) {
            mNetCarSource.cancelTask();
            mNetCarSource = null;
        }
        if (carListnetWork != null) {
            carListnetWork.cancelTask();
            carListnetWork = null;
        }
        if (mSellRecordNetDataJson != null) {
            mSellRecordNetDataJson.cancelTask();
            mSellRecordNetDataJson = null;
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    private void initView() {
        vipButton = (Button) findViewById(R.id.vip_button);
        vipTextView = (TextView) findViewById(R.id.vip);
        popupView = LayoutInflater.from(this).inflate(R.layout.buy_car_popup, null);
        mPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ColorDrawable cd = new ColorDrawable(0x000000);
        mPopupWindow.setBackgroundDrawable(cd);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setOnDismissListener(this);
        popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        nocar_headView = LayoutInflater.from(this).inflate(R.layout.no_car_header, null);
        //设置监听器拦截onItemclick
        nocar_headView.setOnClickListener(this);
        vip_popupView = LayoutInflater.from(this).inflate(R.layout.buy_car_popup1, null);
        vipPopupWindow = new PopupWindow(vip_popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        vipPopupWindow.setBackgroundDrawable(cd);
        vipPopupWindow.setOutsideTouchable(true);
        vip_popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        vipPopupWindow.setOnDismissListener(this);

        mListView = (ListView) findViewById(R.id.list_view);
        headV = LayoutInflater.from(this).inflate(R.layout.new_head_car_ass, null);
        recommed_moreT = (TextView) headV.findViewById(R.id.recommed_more);
        recommed_moreT.setOnClickListener(this);
        lineView = (PriceRegionView) headV.findViewById(R.id.lineView);
        popupTextView = (TextView) headV.findViewById(R.id.popup);
        carNameTextView = (TextView) headV.findViewById(R.id.carName);
        carTimeTextView = (TextView) headV.findViewById(R.id.carTime);
        carPriceTextView = (TextView) headV.findViewById(R.id.carPrice);
        gbTextView = (TextView) headV.findViewById(R.id.gb);
        price_rangeTextView = (TextView) headV.findViewById(R.id.price_range);
        mImageView = (ImageView) headV.findViewById(R.id.car_img);
        cpo_priceT = (TextView) headV.findViewById(R.id.cpo_price);
        dealer_priceT = (TextView) headV.findViewById(R.id.dealer_price);
        private_party_priceT = (TextView) headV.findViewById(R.id.private_party_price);
        mPriceChangeView = (PriceChangeView) headV.findViewById(R.id.change_view);
        priceChangeMain = headV.findViewById(R.id.price_changeMain);
        priceChangeMain.setVisibility(View.GONE);
        num_tv = (TextView)headV.findViewById(R.id.num_tv);
        recommed_ll = (LinearLayout) headV.findViewById(R.id.recommed_ll);

        circleMain = headV.findViewById(R.id.circleMain);
        mCircleView = (CircleView) headV.findViewById(circleView);
        circleMain.setVisibility(View.GONE);
        price_rangeTextView.setOnClickListener(this);
        vipButton.setOnClickListener(this);
        vipTextView.setOnClickListener(this);
        include_sell_record_ll = (LinearLayout) headV.findViewById(R.id.include_sell_record_ll);
        more_ll = (LinearLayout) headV.findViewById(R.id.more_ll);
        sell_record_ll = (LinearLayout) headV.findViewById(R.id.sell_record_ll);
        load_state_tv = (TextView) headV.findViewById(R.id.load_state_tv);
        load_state_img = (ImageView) headV.findViewById(R.id.load_state_img);
        more_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLoadState = !isLoadState;
                addRecordView();
            }
        });
        recommed_tv = (TextView) headV.findViewById(R.id.recommed_tv);
    }

    private void initData() {
        mCarSourceList = new ArrayList<>();
        mAdapter = new CarSourceListAdapter(this);
        mListView.addHeaderView(headV);

        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        assessmentData = AssessmentData.getInstance();
        popupTextView.setOnClickListener(this);
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            String fromType = bundle.getString("type", "");
            if ((MyPushIntentService.RECKONBUY).equals(fromType)) {
                String vaule = bundle.getString("typevalue", "");
                setAssessmentPushData(vaule);
            }
        }
        getData();
    }

    //brand/model/modeldetail/year-month/mileage,形如audi/audi-a4/3621_ah/2008-4/2.50/nanjing
    public void setAssessmentPushData(String value) {
        try {
            String[] datas = value.split("/");
            assessmentData.setBrandSlug(datas[0]);
            assessmentData.setBrandName(datas[0]);
            assessmentData.setModelSlug(datas[1]);
            assessmentData.setModelName("");
            assessmentData.setModelDetailName(getIntent().getStringExtra("description"));
            assessmentData.setModelDetailSlug(datas[2]);
            assessmentData.setMile(datas[4]);
            assessmentData.setCity(getIntent().getStringExtra("city"));
            assessmentData.setStatus("");
            assessmentData.setCar_id("");
            String times[] = datas[3].split("-");
            assessmentData.setYear(times[0]);
            assessmentData.setMonth(times[1]);

        } catch (Exception e) {

        }
    }

    public void getData() {
        if (mNetCarSource == null)
            mNetCarSource = new NetDataJson(this);
        String url = API.assessmentResult;
        mNetCarSource.setUrl(url);
        mNetCarSource.addParam("brand", assessmentData.getBrandSlug());
        mNetCarSource.addParam("model", assessmentData.getModelSlug());
        mNetCarSource.addParam("model_detail", assessmentData.getModelDetailSlug());
        mNetCarSource.addParam("year", assessmentData.getYear());
        mNetCarSource.addParam("month", assessmentData.getMonth());
        mNetCarSource.addParam("city", assessmentData.getCity());
        mNetCarSource.addParam("mileage", assessmentData.getMile());
        mNetCarSource.request("get");
        showProgressDialog();
    }


    private void requestCar() {
        if (carListnetWork == null) {
            carListnetWork = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {

                    Toast.makeText(NewUseCarAssResultActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {


                    JSONArray jsonArray = null;
                    try {
                        jsonArray = json.getJSONArray("car_list");
                        if (0 == jsonArray.length()) {
                            mListView.setAdapter(mAdapter);
                            recommed_ll.setVisibility(View.GONE);

                            return;
                        }
                        getDataFromJsonArray(jsonArray);

                    } catch (JSONException e) {
                        Toast.makeText(NewUseCarAssResultActivity.this, "解析数据异常,请稍后再试", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        carListnetWork.setUrl(API.searchcarfuzzy);
        carListnetWork.addParam("city", assessmentData.getCity());
        carListnetWork.addParam("year", assessmentData.getYear());
        if (!Utils.isStringNull(assessmentData.getBrandSlug()))
            carListnetWork.addParam("brand", assessmentData.getBrandSlug());
        if (!Utils.isStringNull(assessmentData.getModelSlug()))
            carListnetWork.addParam("model", assessmentData.getModelSlug());
        if (!Utils.isStringNull(assessmentData.getModelDetailSlug()))
            carListnetWork.addParam("model_detail", assessmentData.getModelDetailSlug());
        carListnetWork.request("get");
    }


    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
            carSrc.newCity = object.getString("city");
            carSrc.mTitle = object.getString("title");
            carSrc.car_tag = object.getString("car_tag");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.mUrl = carSrc.mThumbnail;
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.dealer_category = object.getString("dealer_category");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");
            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");

            mCarSourceList.add(carSrc);
        }

        if (mCarSourceList.size() != 0) {
            mAdapter.setData(mCarSourceList);
        } else {
            mListView.setAdapter(mAdapter);
            recommed_tv.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        if (v == popupTextView) {
            //买车查价解释
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_buy_help", System.currentTimeMillis(), roll_pages));
            mPopupWindow.showAsDropDown(popupTextView, 0, -popupTextView.getHeight() - popupView.getMeasuredHeight() - 10);
            mHandler.sendEmptyMessageDelayed(1, 5000);
        } else if (v == vipButton) {
//            if (!GPJApplication.getInstance().isLogin()) {
//                Intent intent = new Intent(this, LoginActivity.class);
//                startActivityForResult(intent, LOGINING_FORSEECAR);
//            } else {
            ShowVipDialog();
//            }
        } else if (v == vipTextView) {
            //vip买车解释
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_buy_vipBuy_help", System.currentTimeMillis(), roll_pages));
            vipPopupWindow.showAsDropDown(vipButton, 0, -vipButton.getHeight() - vip_popupView.getMeasuredHeight() - 10);
            mHandler.sendEmptyMessageDelayed(2, 5000);
        } else if (v == price_rangeTextView) {
            Intent intent = new Intent(this, NewCarPriceActivity.class);
            intent.putExtra("title", tilte);
            intent.putExtra("image", imageUrl);
            intent.putExtra("price", price);
            intent.putExtra("city", assessmentData.getCity());
            intent.putExtra("model_detail", assessmentData.getModelDetailSlug());
            intent.putExtra("price_range", price_rangeTextView.getText().toString());
            startActivity(intent);
        }

        switch (v.getId()) {
            case R.id.dialog_close:
                finish();
                break;
            case R.id.dialog_btn:
                if (!GPJApplication.getInstance().isLogin() && getSharedPreferences("GetPhone", MODE_PRIVATE).getBoolean("isShowGetPhoneDialog", true)) {
                    showGetPhoneDialog();
                }
                break;

            //同款车型查看更多
            case R.id.recommed_more:
                finish();
                CarListFilterData.getInstance().clear();
                CarListFilterData data = CarListFilterData.getInstance();
                data.setCity(assessmentData.getCity());
                data.setModelName(assessmentData.getModelName());
                data.setModelSlug(assessmentData.getModelSlug());
                data.setBrandName(assessmentData.getBrandName());
                data.setBrandSlug(assessmentData.getBrandSlug());
                CarListFilterData.getInstance().setIsCleanData(true);
                MainActivity.main.gotocheshi();
                PointRecordManage.getInstance().addPoint(mySelf, "BuyReckonEnterMarket");
                break;

            //同款车型市场零售价
//            case R.id.same_brand_list:
//                Intent intent = new Intent(this, BuyCarVipActivity.class);
//                intent.putExtra("brandSlug", assessmentData.getBrandSlug());
//                intent.putExtra("brandName", assessmentData.getBrandName());
//                intent.putExtra("modelSlug", assessmentData.getModelSlug());
//                intent.putExtra("modelName", assessmentData.getModelName());
//                intent.putExtra("mile", assessmentData.getMile());
//                intent.putExtra("price", avg_buy);
//                startActivity(intent);
////                PointRecordManage.getInstance().addPoint(mySelf,"BuyReckonEnterMarket");
//                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOGINING_FORSEECAR) {
                ShowVipDialog();
            }
        }
    }

    private void ShowVipDialog() {
        //使用VIP购车服务

        Intent intent = new Intent(this, BuyCarVipActivity.class);
        intent.putExtra("brandSlug", assessmentData.getBrandSlug());
        intent.putExtra("brandName", assessmentData.getBrandName());
        intent.putExtra("modelSlug", assessmentData.getModelSlug());
        intent.putExtra("modelName", assessmentData.getModelName());
        intent.putExtra("mile", assessmentData.getMile());
        intent.putExtra("price", avg_buy);
        startActivity(intent);


//        StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_buy_vipBuy", System.currentTimeMillis(), roll_pages));
//        vipBuyCarDialog = new VipBuyCarDialog(this, price);
//        vipBuyCarDialog.show();
    }


    public void gotoVip(String price, String age, String mile) {
        VipBuycarBean mVipBuycarBean = new VipBuycarBean();
        mVipBuycarBean.setPrice(price);
        mVipBuycarBean.setAge(age);
        mVipBuycarBean.setMile(mile);
        mVipBuycarBean.setCity(assessmentData.getCity());
        mVipBuycarBean.setBrand_models(assessmentData.getBrandSlug() + "," + assessmentData.getModelSlug());
        UserManager mUserManager = new UserManager(this);
        mUserManager = mUserManager.LoadUserInfo();
        mVipBuycarBean.setPhone(mUserManager.getPhone());
        mVipBuycarBean.setType("specific");
        Intent intent = new Intent(this, VipRecomendCarActivity.class);
        intent.putExtra("mVipBuycarBean", mVipBuycarBean);
        startActivity(intent);

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position != 0) {
            Intent intent = new Intent();
            CarSource carSource = (CarSource) view.getTag(R.id.tag_second);
            intent.setClass(this, CarBuyDetailActivity.class);
            intent.putExtra("typevalue", String.valueOf(carSource.mId));
            intent.putExtra("type", CarListFragment.FROM_Esimate);
            intent.putExtra("from", "buycarreckon");
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_buyRecommendList", System.currentTimeMillis(), 1f));
            startActivity(intent);

        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        hidenProgressDialog();
        requestCar();
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        mListView.removeHeaderView(headV);
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        //搜索车辆
        requestCar();
        initPriceView(json);
        hidenProgressDialog();
    }

    // 绑定价格到视图上
    private void initPriceView(JSONObject jo) {
        if (!GPJApplication.getInstance().isLogin() && getSharedPreferences("GetPhone", MODE_PRIVATE).getBoolean("isShowGetPhoneDialog", true)) {
            showGetPhoneDialog();
        }
        try {
            tilte = jo.getString("title");
            carNameTextView.setText(tilte);
            price = jo.getString("price_bn");
            num_tv.setText(jo.getInt("same_model_detail_analysed")+"");
            findViewById(R.id.newcar).setVisibility(View.VISIBLE);
            carTimeTextView.setText(jo.getString("year") + "年" + jo.getString("month") + "月上牌/" + jo.getString("mileage") + "万公里");
            carPriceTextView.setText(price + "万");
            JSONArray rangePrice = jo.getJSONArray("4s_price_range");
            if (rangePrice.length() >= 2) {
                carPriceTextView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                carPriceTextView.getPaint().setAntiAlias(true);
                if (rangePrice.get(0).equals(rangePrice.get(1))) {
                    price_rangeTextView.setText(rangePrice.getString(0) + "万");
                } else {
                    price_rangeTextView.setText(rangePrice.getString(0) + "万-" + rangePrice.getString(1) + "万");
                }
            } else {
                price_rangeTextView.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(jo.getString("emission_standard"))) {
                gbTextView.setText("排放标准: " + jo.getString("emission_standard"));
            }
            imageUrl = jo.getString("thumbnail");
            ImageLoad.LoadImage(mImageView, imageUrl, R.drawable.car_loading, R.drawable.car_no, NewUseCarAssResultActivity.this);
            JSONObject jsonObject = jo.getJSONObject("eval_price");
            avg_buy = jsonObject.getString("avg_buy");
            JSONObject jsonPrice = jo.getJSONObject("price_statistics");
            private_party_priceT.setText("¥" + jsonObject.getString("private_party") + "万");
            dealer_priceT.setText("¥" + jsonObject.getString("buy_dealer") + "万");
            cpo_priceT.setText("¥" + jsonObject.getString("buy_cpo") + "万");

            if (jsonPrice.length() == 0) {
                circleMain.setVisibility(View.GONE);
            } else {
                lineView.setAnmiViewGone();
                lineView.setPriceGreenDes("合理价格区间");
                circleMain.setVisibility(View.VISIBLE);
                lineView.setData(jsonObject.getString("avg_buy"),
                        jsonPrice.getString("min_price"),
                        jsonPrice.getString("low_limit"),
                        jsonPrice.getString("high_limit"),
                        jsonPrice.getString("max_price"));

//                lineView.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            priceLoading();
//                        }
//                    }, 1000);


              /*  mCircleView.setData(Double.valueOf(jsonObject.getString("avg_buy")),
                        Double.valueOf(jsonPrice.getString("min_price")),
                        Double.valueOf(jsonPrice.getString("low_limit")),
                        Double.valueOf(jsonPrice.getString("high_limit")),
                        Double.valueOf(jsonPrice.getString("max_price")), false);*/
            }
            List<PriceBean> priceBeans = getPriceChangeList(jo);
            if (priceBeans != null || priceBeans.size() > 0) {
                priceChangeMain.setVisibility(View.VISIBLE);
                mPriceChangeView.setData(priceBeans);
            }
            findViewById(R.id.my_content_view).setVisibility(View.VISIBLE);
            findViewById(R.id.my_content_view1).setVisibility(View.VISIBLE);
        } catch (JSONException e) {
            Toast.makeText(this, "解析数据出错, 请稍后再试", Toast.LENGTH_SHORT).show();
            mListView.removeHeaderView(headV);
        }
    }


    private List<PriceBean> getPriceChangeList(JSONObject jo) {
        List<PriceBean> priceBeans = new ArrayList<>();
        try {
            JSONObject jsonObject = jo.getJSONObject("price_trend");
            if (jsonObject.length() == 0) return null;
            JSONArray history = jsonObject.getJSONArray("history");
            int size;
            size = history.length();
            int maxLength;
            if (size <= 4) {
                maxLength = size;
            } else {
                maxLength = 4;
            }
            for (int i = maxLength - 1; i >= 0; i--) {
                if (i == 4) break;
                double price = Double.valueOf(history.getJSONArray(i).getString(1));
                String[] times = history.getJSONArray(i).getString(0).split("-");
                int year = Integer.parseInt(times[0].substring(2));
                int mouth = Integer.parseInt(times[1]);
                PriceBean priceBean = new PriceBean(price, year, mouth, false);
                priceBeans.add(priceBean);
            }
            JSONArray future = jsonObject.getJSONArray("future");
            size = future.length();
            for (int i = 0; i < size; i++) {
                if (i == 2) break;
                double price = Double.valueOf(future.getJSONArray(i).getString(1));
                int year = Integer.parseInt(future.getJSONArray(i).getString(0).substring(2));
                PriceBean priceBean = new PriceBean(price, year, 0, true);
                priceBeans.add(priceBean);
            }
        } catch (JSONException e) {
            return null;
        }
        return priceBeans;
    }

    @Override
    public void onDismiss() {
        mHandler.removeCallbacksAndMessages(null);
    }

    private void initSellRecord() {
        mSellRecordNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(NewUseCarAssResultActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                mSellRecordBean = gson.fromJson(json, SellRecordBean.class);
                if ("success".equals(mSellRecordBean.getStatus())) {
                    addRecordView();

                } else {
                    Toast.makeText(NewUseCarAssResultActivity.this, mSellRecordBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }, 1);
        mSellRecordNetDataJson.setUrl(API.sell_record);
        mSellRecordNetDataJson.addParam("city", assessmentData.getCity());
        mSellRecordNetDataJson.addParam("brand", assessmentData.getBrandSlug());
        mSellRecordNetDataJson.addParam("model", assessmentData.getModelSlug());
        mSellRecordNetDataJson.addParam("model_detail", assessmentData.getModelDetailSlug());
        mSellRecordNetDataJson.addParam("intent", "buy");
        mSellRecordNetDataJson.request("get");
    }

    private void addRecordView() {
        sell_record_ll.removeAllViews();
        if (mSellRecordBean.getData() == null) {
            return;
        }
        int size = mSellRecordBean.getData().size();
        if (size <= 3) {
            more_ll.setVisibility(View.GONE);
        } else {
            more_ll.setVisibility(View.VISIBLE);
            if (isLoadState) {
                size = 3;
                load_state_tv.setText("查看更多 ");
                load_state_img.setSelected(false);

            } else {
                load_state_tv.setText("收起  ");
                load_state_img.setSelected(true);
            }

        }
        if (size > 0) {
            include_sell_record_ll.setVisibility(View.VISIBLE);
            for (int i = 0; i < size; i++) {
                View view = LayoutInflater.from(this).inflate(R.layout.sell_record_item, null);
                TextView model_txt = (TextView) view.findViewById(R.id.model_txt);
                TextView carName = (TextView) view.findViewById(R.id.carName);
                TextView price = (TextView) view.findViewById(R.id.price);
                TextView detail = (TextView) view.findViewById(R.id.detail);
                TextView time = (TextView) view.findViewById(R.id.time);
                SellRecordBean.DataBean data = mSellRecordBean.getData().get(i);
                if (data.getModel_detail_slug().equals(assessmentData.getModelDetailSlug())) {
                    model_txt.setVisibility(View.VISIBLE);
                } else {
                    model_txt.setVisibility(View.GONE);
                }
                carName.setText(data.getModel_zh() + " " + data.getModel_detail_zh());
                price.setText(data.getPrice());
                detail.setText(data.getMile() + "万公里 | " + data.getYear() + "年上牌 | " + data.getCity());
                time.setText("成交于" + TimeUtils.timeFormat(data.getDeal_time()));
                sell_record_ll.addView(view);
            }
        }
    }

    private void showGetPhoneDialog() {
        if (getPhoneDialog == null) {
            getPhoneDialog = new GetPhoneDialog(NewUseCarAssResultActivity.this);
            getPhoneDialog.setOnPickResultListener(new GetPhoneDialog.OnPickResultListener() {
                @Override
                public void onResult(int result) {
                    finish();
                }
            });
        }
        getPhoneDialog.show(0);
        MobclickAgent.onEvent(this,"ReckonMobileAlertShow");
    }
}
